package dao;

import Utils.C3P0Utils;
import domain.Product;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * Created by guo on 2017/10/23.
 */
public class ProductImpl implements ProductDao {
    @Override
    public List<Product> findAll() {
        QueryRunner runner=new QueryRunner(C3P0Utils.getDs());
        String sql="select * from product";
        List list=null;
        try {
            list=(List) runner.query(sql,new BeanListHandler(Product.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public Boolean Add(String pname, Double market_price, Double shop_price, String pdesc) throws SQLException {
        QueryRunner runner=new QueryRunner(C3P0Utils.getDs());
        String sql="insert into product(pname,market_price,shop_price,pdesc)values(?,?,?,?)";
        int num=runner.update(sql,pname,market_price,shop_price,pdesc);
        if(num>0)
        {
            return true;
        }
        else
            return false;
    }

    @Override
    public Boolean Delete(int pid) throws SQLException {
        QueryRunner runner=new QueryRunner(C3P0Utils.getDs());
        String sql="delete  from product where pid=?";
        int num=runner.update(sql,pid);
        if(num>0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    @Override
    public Boolean Update(String pname, Double market_price, Double shop_price, String pdesc,int pid) throws SQLException {
        QueryRunner runner=new QueryRunner(C3P0Utils.getDs());
        String sql="update product set pname=?,market_price=?,shop_price=?,pdesc=? where pid=?";
        int num=runner.update(sql,pname,market_price,shop_price,pdesc,pid);
        if(num>0)
        {
            return true;
        }
        else
            return false;
    }
}
